package cn.cqautotest.cqviehelper.adapters;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import cn.cqautotest.cqviehelper.R;
import cn.cqautotest.cqviehelper.presenter.SpeakPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.InnerHolder> {

    private List<String> mObjects = new ArrayList<>();
    private Context mContext;
    private final TextToSpeech mTextToSpeech;

    public ChatAdapter() {
        SpeakPresenter speakPresenter = SpeakPresenter.getInstance();
        mTextToSpeech = speakPresenter.getTextToSpeech();
    }

    public void setObjects(List<String> objects) {
        mObjects = objects;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return mObjects.size();
    }

    public String getPositionData(int position) {
        return mObjects.get(position);
    }

    @NonNull
    @Override
    public InnerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        View itemView = LayoutInflater.from(mContext).inflate(R.layout.item_rv_chat, parent, false);
        return new InnerHolder(itemView);
    }

    private long utteranceId = 0;
    @Override
    public void onBindViewHolder(@NonNull InnerHolder holder, int position) {
        View itemView = holder.itemView;
        TextView tvMessage = holder.tvMessage;
        String message = getPositionData(position);
        tvMessage.setText(message);
        itemView.setOnClickListener(v -> {
            mTextToSpeech.speak(message, TextToSpeech.QUEUE_FLUSH, null, String.valueOf(utteranceId));
            utteranceId++;
        });
    }

    public static class InnerHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tvMessage)
        TextView tvMessage;

        public InnerHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
